package com.busfm.activity;

import com.busfm.R;
import com.busfm.listener.NetResponseListener;
import com.busfm.model.UserEntity;
import com.busfm.net.NetWorkManager;
import com.busfm.provider.UserAccountManager;
import com.busfm.util.Constants;
import com.busfm.util.InstrumentUtil;
import com.busfm.util.LogUtil;
import com.busfm.util.PatternUtil;
import com.busfm.util.Utilities;
import com.mobclick.android.MobclickAgent;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends BaseActivity implements OnClickListener {
    EditText etEmail;
    EditText etPwd;
    Button btnLogin;
    Button btnRegister;
    Button btnFgtPwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        setupView();
    }

    @Override
    protected void onResume() {
        if (UserAccountManager.isSignIn(this)) {
            this.finish();
        }
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
    }

    private void initView() {
        etEmail = (EditText) findViewById(R.id.activity_login_et_email);
        etPwd = (EditText) findViewById(R.id.activity_login_et_pwd);
        btnLogin = (Button) findViewById(R.id.activity_login_btn_login);
        btnRegister = (Button) findViewById(R.id.activity_login_btn_register);
        btnFgtPwd = (Button) findViewById(R.id.activity_login_btn_fgtpwd);
    }

    private void setupView() {
        btnLogin.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        btnFgtPwd.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_login_btn_login :
                if (isIlleageLoginData()) {
                    login();
                }
                break;
            case R.id.activity_login_btn_register :
                InstrumentUtil.launchRegister(this);
                break;
            case R.id.activity_login_btn_fgtpwd :
                InstrumentUtil.launchFgtPwd(this);
                break;
            default:
                break;
        }
    }

    /**
     * check whether the input data is illeage
     * 
     * @return
     */
    private boolean isIlleageLoginData() {
        boolean result = true;
        if (Utilities.isEmpty(etEmail.getText().toString())) {
            etEmail.setError(getString(R.string.activity_login_email_empty_error));
            result = false;
        } else if (!PatternUtil.EMAIL_ADDRESS_PATTERN.matcher(etEmail.getText().toString()).find()) {
            etEmail.setError(getString(R.string.activity_login_email_format_error));
            result = false;
        }

        if (Utilities.isEmpty(etPwd.getText().toString())) {
            etPwd.setError(getString(R.string.activity_login_password_empty_error));
            result = false;
        } else if (!PatternUtil.PWD_PATTERN.matcher(etPwd.getText().toString()).find()) {
            etPwd.setError(getString(R.string.activity_login_password_format_error));
            result = false;
        }

        return result;
    }

    private void login() {
        showDialog(DIALOG_WAIT);
        NetWorkManager.login(this, etEmail.getText().toString(), etPwd.getText().toString());
    }

    private void setLoginInfo(UserEntity userEntity) {
        UserAccountManager.saveUserData(this, userEntity, etPwd.getText().toString());
    }

    private void removeWaitingDialog() {
        try {
            removeDialog(DIALOG_WAIT);
        } catch (Exception e) {
        }
    }

    @Override
    public void clientDidLogin(NetResponseListener mClientListener, UserEntity userEntity) {
        removeWaitingDialog();
        try{
            if (null != userEntity && userEntity.getErrorMsg().equals("")) {
                setLoginInfo(userEntity);
                setResult(RESULT_OK);
                finish();
                Toast.makeText(this, getString(R.string.activity_login_suceess), Toast.LENGTH_SHORT).show();
            } else if (!userEntity.getErrorMsg().equals("")) {
                Toast.makeText(this, userEntity.getErrorMsg(), Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e) {
            LogUtil.i(Constants.TAG, e.getMessage());
        }
        super.clientDidLogin(mClientListener, userEntity);
    }

    @Override
    public void clientDidFailWithError(
        NetResponseListener mClientListener, int mOp, int scUnknown, String localizedMessage) {
        removeWaitingDialog();
        Toast.makeText(this, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
        super.clientDidFailWithError(mClientListener, mOp, scUnknown, localizedMessage);
//        setResult(RESULT_CANCELED);
//        finish();
    }
    
    @Override
    public void clientDidRequireAuthentication(NetResponseListener mClientListener) {
        removeWaitingDialog();
        Toast.makeText(this, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void clientNoNeedUpdate(NetResponseListener mClientListener) {
        removeWaitingDialog();
        Toast.makeText(this, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void clientNoEnoughCredit(NetResponseListener mClientListener) {
        removeWaitingDialog();
        Toast.makeText(this, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
    }
}
